/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Anna SAELEE
 */
public class Update extends HttpServlet {

    private String typeMss;
    private String update;
    private String toHome = "<br/>Retourner à la page d'<a href=\"index.jsp\">Acceuille</a>";
    private String err = "<br/>Désolé, ne pas pourvoir connecter au serveur<br/>";
    private String prePage;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException, AddressException {
        response.setContentType("text/html;charset=UTF-8");
        Connection conn;
        Statement stmt;
        ResultSet rs;
        PrintWriter out = response.getWriter();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dormitorymanagement", "root", "root");
            stmt = conn.createStatement();

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Update</title>");
            out.println("</head>");
            out.println("<body>");

            typeMss = request.getParameter("typeMss");
            if (typeMss.equals("moveOut")) {
                String deleteUsr = request.getParameter("deleteUsr");
                prePage = "<br/>Retourner à la page <a href=\"infoStudent.jsp\">List des étudiants</a>";

                update = "SELECT * FROM account WHERE username='" + deleteUsr + "'";
                rs = stmt.executeQuery(update);
                if (!rs.next()) {
                    out.println(err);
                    out.println(toHome);
                    out.println(prePage);
                } else {
                    String status = request.getParameter("usrStatus");
                    String room = rs.getString("r_number");
                    if (status.equals("1")) {
                        update = "UPDATE account SET r_number=NULL, status = 0 WHERE username ='" + deleteUsr + "'  ";

                        int i = stmt.executeUpdate(update);
                        update = "UPDATE room SET n_place = n_place-1, available=available+1 WHERE r_number='" + room + "'";
                        int j = stmt.executeUpdate(update);
                        if (i == 1) {
                            out.println("Réussi à mettre à jour le status(inavailable) du compte de l'utilisateur: " + deleteUsr);
                            out.println(toHome);
                            out.println(prePage);
                        } else {
                            out.println(err);
                        }
                    } else {
                        update = "UPDATE account SET status='1' WHERE username='" + deleteUsr + "'";
                        int i = stmt.executeUpdate(update);
                        if (i == 1) {
                            out.println("Réussi à mettre à jour le status(available) du compte de l'utilisateur: " + deleteUsr);
                            out.println(toHome);
                            out.println(prePage);
                        } else {
                            out.println(err);
                        }
                    }
                }
            } else if (typeMss.equals("enroll")) {
                String lastname = request.getParameter("lastname");
                String firstname = request.getParameter("firstname");
                String HBD = request.getParameter("HBD");
                String room = request.getParameter("room");
                prePage = "<br/> Retourner à la page <a href=\"enroll.jsp\">S'incrire un étudiant à une chambre</a>";

                update = "UPDATE account SET r_number='" + room + "' WHERE lastname='" + lastname + "' AND firstname='" + firstname + "' AND birthday='" + HBD + "'";
                int i = stmt.executeUpdate(update);
                if (i == 1) {
                    out.println("Réussi à s'inscrire l'étudiant: " + lastname + " " + firstname + " dans la chambre " + room);
                    out.println(toHome);
                    out.println(prePage);
                    update = "UPDATE room SET n_place = n_place+1, available = available-1 WHERE r_number='" + room + "'";
                    int j = stmt.executeUpdate(update);
                    if (j == 1) {
                        out.println("<br/>Réussi à mettre à jour l'espace de la chambre");
                    } else {
                        out.println("<br/>Ne pas pouvoir mettre à jour l'espace de la chambre");
                    }
                } else {
                    out.println(err);
                }
            } else if (typeMss.equals("changeRoom")) {
                String username = request.getParameter("selectedUsr");
                String room = request.getParameter("room");
                String oldroom = request.getParameter("oldroom");
                prePage = "<br/> Retourner à la page <a href=\"infoStudent.jsp\">Information des étudiants</a>";

                update = "UPDATE account SET r_number='" + room + "' WHERE username='" + username + "'";
                int i = stmt.executeUpdate(update);
                if (i == 1) {
                    out.println("Réussi à s'inscrire l'étudiant du compte: " + username + " dans la chambre " + room);
                    out.println(toHome);
                    out.println(prePage);
                    update = "UPDATE room SET n_place=n_place-1, available=available+1 WHERE r_number='" + oldroom + "'";
                    int j = stmt.executeUpdate(update);
                    update = "UPDATE room SET n_place=n_place+1, available=available-1 WHERE r_number='" + room + "'";
                    int k = stmt.executeUpdate(update);
                    if (j == 1 && k == 1) {
                        out.println("<br/>Réussi à mettre à jour l'espace de la chambre");
                    } else {
                        out.println("<br/>Ne pas pouvoir mettre à jour l'espace de la chambre");
                    }
                } else {
                    out.println(update);
                    out.println(err);
                }
            } else if (typeMss.equals("updateNews")) {
                String nid = request.getParameter("nid");
                String subject = request.getParameter("subject");
                String detail = request.getParameter("detail");
                prePage = "<br/>Retourner à la page <a href=\"listAnnonce.jsp\">List des nouvelles</a>";

                update = "UPDATE news SET subject='" + subject + "', detail='" + detail + "' WHERE nid=" + 1;
                int i = stmt.executeUpdate(update);
                if (i == 1) {
                    ServletContext context = getServletContext();
                    String host = context.getInitParameter("host");
                    String port = context.getInitParameter("port");
                    String user = context.getInitParameter("user");
                    String pass = context.getInitParameter("pass");

                    String sql = "SELECT email FROM account";
                    rs = stmt.executeQuery(sql);
                    while (rs.next()) {
                        EmailUtility.sendEmail(host, port, user, pass, rs.getString("email"), subject, detail);
                    }

                    sql = "SELECT email FROM recieve_news";
                    rs = stmt.executeQuery(sql);
                    while (rs.next()) {
                        EmailUtility.sendEmail(host, port, user, pass, rs.getString("email"), subject, detail);
                    }
                    out.println("Réussi à mettre à jour la nouvelle<br/>");
                    out.println(toHome);
                    out.println(prePage);
                } else {
                    out.println(err);
                }
            } else if (typeMss.equals("changePwd")) {
                prePage = "<br/>Retourner à la page <a href=\"profile.jsp\">Profil</a>";
                String username = request.getParameter("username");
                String oldPwd = request.getParameter("oldPwd");
                String newPwd1 = request.getParameter("newPwd1");
                String newPwd2 = request.getParameter("newPwd2");
                String sql = "SELECT password FROM account WHERE username='" + username + "'";
                rs = stmt.executeQuery(sql);
                while (rs.next()) {
                    if (rs.getString("password").equals(oldPwd)) {
                        if (newPwd1.equals(newPwd2)) {
                            update = "UPDATE account SET password='" + newPwd1 + "' WHERE username='" + username + "'";
                            int i = stmt.executeUpdate(update);
                            if (i == 1) {
                                out.println("Réussi à mettre à jour la nouvelle mot de passe<br/>");
                                out.println(toHome);
                                out.println(prePage);
                            } else {
                                out.println(err);
                            }
                        } else {
                            out.println("Les nouvelles mot de passe ne sont pas identique!");
                            out.println(toHome);
                            out.println(prePage);
                        }
                    } else {
                        out.println("Vous avez entré le mot de passe invalide!");
                        out.println(toHome);
                        out.println(prePage);
                    }
                }
            } else if (typeMss.equals("changeMail")) {
                prePage = "<br/>Retourner à la page <a href=\"profile.jsp\">Profil</a>";
                String username = request.getParameter("username");
                String newMail1 = request.getParameter("newMail1");
                String newMail2 = request.getParameter("newMail2");
                String password = request.getParameter("password");
                String sql = "SELECT password FROM account WHERE username='" + username + "'";
                rs = stmt.executeQuery(sql);
                while (rs.next()) {
                    if (rs.getString("password").equals(password)) {
                        if (!newMail1.equals("") && !newMail2.equals("") && newMail1.equals(newMail2)) {
                            update = "UPDATE account SET email='" + newMail1 + "' WHERE username='" + username + "'";
                            int i = stmt.executeUpdate(update);
                            if (i == 1) {
                                out.println("Réussi à mettre à jour la nouvelle courriel<br/>");
                                out.println(toHome);
                                out.println(prePage);
                            } else {
                                out.println(err);
                            }
                        } else {
                            out.println("Les nouvelles courriels ne sont pas identique!");
                            out.println(toHome);
                            out.println(prePage);
                        }
                    } else {
                        out.println("Vous avez entré le mot de passe invalide!");
                        out.println(toHome);
                        out.println(prePage);
                    }
                }
            } else if (typeMss.equals("confirmMail")) {
                String username = request.getParameter("username");
                update = "UPDATE account SET status=1 WHERE username='" + username + "'";
                int i = stmt.executeUpdate(update);
                if (i == 1) {
                    out.println("Réussi à activer votre compte<br/>");
                    out.println(toHome);
                } else {
                    out.println(err);
                }
            }
//            out.println(update);

            out.println("</body>");
            out.println("</html>");
        } catch (MessagingException ex) {
            Logger.getLogger(Update.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Update.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Update.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AddressException ex) {
            Logger.getLogger(Update.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Update.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Update.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AddressException ex) {
            Logger.getLogger(Update.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
